import axios from 'axios';
import {ElMessage} from 'element-plus';

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8088/api',
    timeout: 10000
});


// 获取所有用户
axiosInstance.fetchAllUsers = async () => {
    try {
        const response = await axiosInstance.get('/user/get_all');
        return response.data.data; // 返回成功获取的用户列表
    } catch (error) {
        console.error(error);
        ElMessage.error('获取用户列表失败');
        throw error; // 抛出错误
    }
};

// 根据 ID 获取用户
axiosInstance.fetchUserByUname = async (uname) => {
    try {
        const response = await axiosInstance.get(`/user/get_by_uname/${uname}`);
        return response.data.data; // 返回成功获取的用户信息
    } catch (error) {
        console.error(error);
        ElMessage.error(`获取用户  ${uname} 失败`);
        throw error; // 抛出错误
    }
};

// 根据 ID 获取用户
axiosInstance.fetchUserById = async (userId) => {
    try {
        const response = await axiosInstance.get(`/user/get_by_id/${userId}`);
        return response.data.data; // 返回成功获取的用户信息
    } catch (error) {
        console.error(error);
        ElMessage.error(`获取用户 ID ${userId} 失败`);
        throw error; // 抛出错误
    }
};

// 添加用户
axiosInstance.addUser = async (user) => {
    try {
        const response = await axiosInstance.post('/user/add_user', user);
        ElMessage.success('用户添加成功');
        return response.data.data; // 返回添加成功的响应
    } catch (error) {
        console.error(error);
        ElMessage.error('添加用户失败');
        throw error; // 抛出错误
    }
};

// 更新用户
axiosInstance.updateUser = async (userId, userDTO) => {
    try {
        const response = await axiosInstance.put(`/user/update_user/${userId}`, userDTO);
        ElMessage.success('用户信息更新成功');
        return response.data.data; // 返回更新成功的响应
    } catch (error) {
        console.error(error);
        ElMessage.error(`更新用户 ID ${userId} 失败`);
        throw error; // 抛出错误
    }
};

// 删除用户
axiosInstance.deleteUser = async (userId) => {
    try {
        const response = await axiosInstance.delete(`/user/delete_user/${userId}`);
        ElMessage.success('用户删除成功');
        return response.data.data; // 返回删除成功的响应
    } catch (error) {
        console.error(error);
        ElMessage.error(`删除用户 ID ${userId} 失败`);
        throw error; // 抛出错误
    }
};


export default axiosInstance;
